
// ProcessListDlg.cpp : implementation file
//

#include "stdafx.h"
#include "ProcessList.h"
#include "ProcessListDlg.h"
#include "memwalk.h"
#include <Windows.h>

#pragma comment(lib,"psapi")


DWORD transactionPID= NULL; //Global Var for PID Transport ;)
int itemSelection = NULL;

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CProcessListDlg dialog

CProcessListDlg::CProcessListDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CProcessListDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CProcessListDlg)
		// NOTE: the ClassWizard will add member initialization here
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	pModuleToTerminate = NULL;
}

void CProcessListDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CProcessListDlg)
	DDX_Control(pDX, IDC_LIST1, m_ListCtrl);
	DDX_Control(pDX, IDC_TREE1, pCtrl);
	//}}AFX_DATA_MAP
	DDX_Control(pDX, IDC_LIST2, m_ListCtrl2);
	DDX_Control(pDX, IDC_LIST3, m_List);
	DDX_Control(pDX, IDC_LIST4, m_List4);
}

BEGIN_MESSAGE_MAP(CProcessListDlg, CDialog)
	//{{AFX_MSG_MAP(CProcessListDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_NOTIFY(TVN_SELCHANGED, IDC_TREE1, OnSelchangedTree)
	ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
	//}}AFX_MSG_MAP
	ON_BN_CLICKED(IDC_BUTTON2, &CProcessListDlg::OnBnClickedButton2)
	ON_BN_CLICKED(IDC_BUTTON3, &CProcessListDlg::OnBnClickedButton3)
	ON_NOTIFY(LVN_ITEMCHANGED, IDC_LIST2, &CProcessListDlg::OnLvnItemchangedList2)
	ON_NOTIFY(HDN_ITEMCLICK, 0, &CProcessListDlg::OnHdnItemclickList2)
	ON_BN_CLICKED(IDC_BUTTON4, &CProcessListDlg::OnBnClickedButton4)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CProcessListDlg message handlers

BOOL CProcessListDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

		
	m_ListCtrl.InsertColumn(0, "Text", LVCFMT_CENTER, 100);
	m_ListCtrl.InsertColumn(1, "Description", LVCFMT_LEFT, 300);
	
	
	m_ListCtrl2.InsertColumn(0,"Text",LVCFMT_CENTER,300);
	
	m_List.InsertColumn(0,"Name",LVCFMT_CENTER,200);

	m_List4.InsertColumn(0, "Text", LVCFMT_CENTER, 100);
	m_List4.InsertColumn(1, "Description", LVCFMT_LEFT, 300);


	VERIFY( m_ImageList.Create( GetSystemMetrics( SM_CXSMICON ), 
                                GetSystemMetrics( SM_CYSMICON ), 
                                ILC_COLOR32 | ILC_MASK, 
                                0, 
                                20 ));
	
    pCtrl.SetImageList( &m_ImageList, TVSIL_NORMAL );
	VERIFY( m_Bitmap.LoadBitmap( IDB_BITMAP1));
    m_ImageList.Add( &m_Bitmap, RGB( 255, 0, 255 ));
	
	LoadProcesses();
	ShowWindow(SW_SHOWNORMAL);
	return TRUE;
}

void CProcessListDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}


void CProcessListDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}


HCURSOR CProcessListDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

//BOOL CProcessListDlg::GetFileTimeAsString(LPFILETIME pFt, char * pszTime, unsigned cbIn)
//{
//	FILETIME ftLocal;
//	SYSTEMTIME st;
//
//	if(!FileTimeToLocalFileTime( pFt, &ftLocal))
//		return FALSE;
//
//	if(!FileTimeToSystemTime( &ftLocal, &st))
//		return FALSE;
//
//	char szTemp[12];
//
//	wsprintf(szTemp, "%02u:%02u:%02u", st.wHour, st.wMinute, st.wSecond);
//	lstrcpyn(pszTime, szTemp, cbIn);	
//	return true;
//}
//
//BOOL CProcessListDlg::GetFileDateAsString(LPFILETIME pFt, char * pszDate, unsigned cbIn)
//{
//	FILETIME ftLocal;
//	SYSTEMTIME st;
//
//	if(!FileTimeToLocalFileTime(pFt, &ftLocal))
//		return FALSE;
//
//	if(!FileTimeToSystemTime(&ftLocal, &st))
//		return FALSE;
//
//	char szTemp[12];
//
//	wsprintf(szTemp, "%02u/%02u/%04u",	st.wMonth, st.wDay, st.wYear);
//	lstrcpyn(pszDate, szTemp, cbIn); 
//
//	return true;
//}


void CProcessListDlg::UpdateProcessTime(DWORD processID)
{
	HANDLE hProcess;
	FILETIME ftCreate, ftExit, ftKernel, ftUser;
	SYSTEMTIME stKernel, stUser;
	CString strName, strData;

	hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE,processID);

	if (hProcess == INVALID_HANDLE_VALUE)
	{
		AfxMessageBox("Unable to obtain the specified process handle");
		return;
	}

	if(GetProcessTimes(hProcess,&ftCreate,&ftExit, &ftKernel,&ftUser))
	{
		COleDateTime timeNow = COleDateTime::GetTickCount();
		COleDateTime timeCreation = ftCreate;
		COleDateTimeSpan timeDifference = timeNow - timeCreation;

		strData.Format("%02d/%02d/%d @ %02d:%02d:%02d",
				timeCreation.GetMonth(),
				timeCreation.GetDay(),
				timeCreation.GetYear(),
				timeCreation.GetHour(),
				timeCreation.GetMinute(),
				timeCreation.GetSecond());
	m_ListCtrl.InsertItem(LVIF_STATE|LVIF_TEXT,16,"CreationTime:" + strData,0,LVIS_SELECTED,0,0); //Creation Time
	m_ListCtrl.SetItemText(16,1,strData);

		strData.Format("%ud %uh %um %us",
				timeDifference.GetDays(),
				timeDifference.GetHours(),
				timeDifference.GetMinutes(),
				timeDifference.GetSeconds());
	m_ListCtrl.InsertItem(LVIF_STATE|LVIF_TEXT,17,"RunningTime:" + strData,0,LVIS_SELECTED,0,0); //Running Time
	m_ListCtrl.SetItemText(17,1,strData);

		FileTimeToSystemTime(&ftKernel,&stKernel);
		strData.Format("%uh %um %us",
				stKernel.wHour,
				stKernel.wMinute,
				stKernel.wSecond);
	m_ListCtrl.InsertItem(LVIF_STATE|LVIF_TEXT,18,"KernelTime:" + strData,0,LVIS_SELECTED,0,0); //Kernel Time
	m_ListCtrl.SetItemText(18,1,strData);

		FileTimeToSystemTime(&ftUser,&stUser);
		strData.Format("%uh %um %us",
				stUser.wHour,
				stUser.wMinute,
				stUser.wSecond);
	m_ListCtrl.InsertItem(LVIF_STATE|LVIF_TEXT,20,"UserTime" +strData,0,LVIS_SELECTED,0,0); // User Time
	m_ListCtrl.SetItemText(19,1,strData);				
	}

	else
	{
		AfxMessageBox("Unable to Get Process Timings!");
		return;
	}
}


// Catch here the selected process!!!
void CProcessListDlg::OnSelchangedTree(NMHDR* pNMHDR, LRESULT* pResult) 
{
	// Clear Items
	m_ListCtrl.DeleteAllItems();  // General Process/Module Information
	m_ListCtrl2.DeleteAllItems(); // Module Lister
	m_List.DeleteAllItems();      // Functions Lister

	pCtrl.SetRedraw(FALSE);
	NM_TREEVIEW* pNMTreeView = (NM_TREEVIEW*)pNMHDR;
	CModuleDetails *pModuleInfo = reinterpret_cast<CModuleDetails *> (pCtrl.GetItemData( pNMTreeView->itemNew.hItem ));
//	*pModuleInfo2 = reinterpret_cast<CModuleDetails *> (pCtrl.GetItemData( pNMTreeView->itemNew.hItem ));
	CString strText;
	
	if(pModuleInfo) //Watch here to add modules to the Second List!
	{
		CEnumProcessList * m_listp = new CEnumProcessList(pModuleInfo->pProcessID);
		for(POSITION modulePos1 = m_listp->GetHeadPosition();modulePos1!=NULL;)
		{
			CModuleDetails* pModuleData = new CModuleDetails;
			pModuleData = m_listp->GetNext(modulePos1);
			int nIndex = m_ImageList.Add(pModuleData->GetAssociatedIcon()); 
			/*
			nIndex = nIndex ? nIndex :20;
			HTREEITEM hProcessModu = pCtrl.InsertItem(pModuleData->GetFullFileName(),nIndex,nIndex,pNMTreeView->itemNew.hItem);						
			pCtrl.SetItemData( hProcessModu, reinterpret_cast<DWORD>(pModuleData));
			*/
			m_ListCtrl2.InsertItem(LVIF_TEXT|LVIF_STATE, nIndex,pModuleData->GetFullFileName(),0, LVIS_SELECTED,0, 0);
		}


		if(pModuleInfo->IsProcessTrue())
			GetDlgItem(IDC_BUTTON1)->EnableWindow(TRUE);
		else
			GetDlgItem(IDC_BUTTON1)->EnableWindow(FALSE);
	}

	if(pModuleInfo)
	{		
		m_ListCtrl.InsertItem(LVIF_TEXT|LVIF_STATE, 0,"Module Name",0, LVIS_SELECTED,0, 0);
		m_ListCtrl.SetItemText(0, 1, pModuleInfo->GetModuleName());

		transactionPID = pModuleInfo->pProcessID;

		m_ListCtrl.InsertItem(LVIF_TEXT|LVIF_STATE, 1,"Module Path",0, LVIS_SELECTED,0, 0);
		m_ListCtrl.SetItemText(1, 1, pModuleInfo->GetFullFileName());
		
		m_ListCtrl.InsertItem(LVIF_TEXT|LVIF_STATE, 2,"Version",0, LVIS_SELECTED,0, 0);
		m_ListCtrl.SetItemText(2, 1, pModuleInfo->GetFileVersion());

		m_ListCtrl.InsertItem(LVIF_TEXT|LVIF_STATE, 3,"File Size",0, LVIS_SELECTED,0, 0);
		CString strFileSize;
		strFileSize.Format("%ld",pModuleInfo->GetFileSize());
		m_ListCtrl.SetItemText(3, 1,strFileSize);

		m_ListCtrl.InsertItem(LVIF_TEXT|LVIF_STATE, 4,"Company",0, LVIS_SELECTED,0, 0);
		m_ListCtrl.SetItemText(4, 1, pModuleInfo->GetCompanyName());

		m_ListCtrl.InsertItem(LVIF_TEXT|LVIF_STATE, 5,"Product Name",0, LVIS_SELECTED,0, 0);
		m_ListCtrl.SetItemText(5, 1, pModuleInfo->GetProductName());

		m_ListCtrl.InsertItem(LVIF_TEXT|LVIF_STATE, 6,"Description",0, LVIS_SELECTED,0, 0);
		m_ListCtrl.SetItemText(6, 1, pModuleInfo->GetFileDescription());

		m_ListCtrl.InsertItem(LVIF_TEXT|LVIF_STATE,7,"LegalCopyright",0,LVIS_SELECTED,0,0);
		m_ListCtrl.SetItemText(7,1,pModuleInfo->GetLegalCopyright());

		m_ListCtrl.InsertItem(LVIF_TEXT|LVIF_STATE,8,"LegalTradeMarks",0,LVIS_SELECTED,0,0);
		m_ListCtrl.SetItemText(8,1,pModuleInfo->GetLegalTrademarks());

		m_ListCtrl.InsertItem(LVIF_STATE|LVIF_TEXT,9,"PrivateBuild",0,LVIS_SELECTED,0,0);
		m_ListCtrl.SetItemText(9,1,pModuleInfo->GetPrivateBuild());

		m_ListCtrl.InsertItem(LVIF_STATE|LVIF_TEXT,10,"InternalFileName",0,LVIS_SELECTED,0,0);
		m_ListCtrl.SetItemText(10,1,pModuleInfo->GetInternalName());

		m_ListCtrl.InsertItem(LVIF_STATE|LVIF_TEXT,11,"OriginalFileName",0,LVIS_SELECTED,0,0);
		m_ListCtrl.SetItemText(11,1,pModuleInfo->GetOriginalFilename());		

		m_ListCtrl.InsertItem(LVIF_STATE|LVIF_TEXT,12,"ProductVersion",0,LVIS_SELECTED,0,0);
		m_ListCtrl.SetItemText(12,1,pModuleInfo->GetProductVersion());

		m_ListCtrl.InsertItem(LVIF_STATE|LVIF_TEXT,13,"Comments",0,LVIS_SELECTED,0,0);
		m_ListCtrl.SetItemText(13,1,pModuleInfo->GetComments());

		m_ListCtrl.InsertItem(LVIF_STATE|LVIF_TEXT,15,"SpecialBuild",0,LVIS_SELECTED,0,0);
		m_ListCtrl.SetItemText(15,1,pModuleInfo->GetSpecialBuild());

		
		CString str;
		str.Format(_T("%04X"),pModuleInfo->pProcessID);
		m_ListCtrl.InsertItem(LVIF_STATE|LVIF_TEXT,20,"Pid: " + str,0,LVIS_SELECTED,0,0);
		m_ListCtrl.SetItemText(20,1,str);
		

		// Process Timings

		UpdateProcessTime(pModuleInfo->pProcessID); // From Item 15 to 20
		}

	pCtrl.SetRedraw(TRUE);
	*pResult = 0;
}


BOOL CProcessListDlg::LoadProcesses()
{
	pCtrl.DeleteAllItems();
	pCtrl.SetRedraw(FALSE);
	int m_nInitialImageCount = 1;
	const int nNewImageCount = m_ImageList.GetImageCount();
    for( int nIndex = nNewImageCount; nIndex > m_nInitialImageCount; --nIndex )
    {
        VERIFY( m_ImageList.Remove( nIndex - 1 ));
    }

	HTREEITEM root = pCtrl.InsertItem(_T("Processes List"),0,0,NULL);
		CEnumProcessList * m_listp = new CEnumProcessList;;

	for(POSITION modulePos = m_listp->GetHeadPosition();modulePos!=NULL;)
	{	
		CModuleDetails* pModuleData = new CModuleDetails;
		pModuleData	= m_listp->GetNext(modulePos);
		int nIndex = m_ImageList.Add(pModuleData->GetAssociatedIcon());		
        nIndex = nIndex ? nIndex :20;
		HTREEITEM hProcess = pCtrl.InsertItem(pModuleData->GetModuleName(),nIndex,nIndex,root);
		pCtrl.SetItemData(hProcess, reinterpret_cast<DWORD>(pModuleData));
	}
	pCtrl.SetRedraw(TRUE);
	pCtrl.Expand(root,TVE_EXPAND);

	


	return TRUE;
}

void CProcessListDlg::OnButton1() 
{	
	// START - Declarations for Process Memory Dumper Engine -   
	MEMORY_BASIC_INFORMATION mbi;
	LPVMOBJECT lpList;
	SYSTEM_INFO si;
	LPVOID lpMem, lpUncommited, memStep;
	LPVOID readBuff;	
	DWORD dwSize, dwIndex, dwBread, dwBwrite;
	HANDLE hProcess;
	HANDLE hFile;
	// END - Declarations for Process Memory Dumper Engine -

	HTREEITEM hItem  = pCtrl.GetSelectedItem();

	if(hItem == NULL)
	{
		AfxMessageBox("No Item Selected!");
		return;
	}

	CModuleDetails *pModuleInfo = reinterpret_cast<CModuleDetails *> (pCtrl.GetItemData(hItem ));
	if(pModuleInfo->IsProcessTrue())
	{
		GetDlgItem(IDC_BUTTON1)->EnableWindow(FALSE);
		hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_VM_OPERATION,
			NULL, pModuleInfo->pProcessID);
		if( hProcess == NULL)
		{
			AfxMessageBox("Failed to open the Process");			
			return;
		}

		CString fileName = pModuleInfo->GetModuleName();		
		fileName = fileName + ".dmp";
		LPCSTR dumpFineName =(LPCSTR)(LPCTSTR) fileName;		
		hFile = CreateFileA(dumpFineName ,FILE_ALL_ACCESS, FILE_SHARE_WRITE, NULL,
			OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);		

		if(hFile == INVALID_HANDLE_VALUE)
		{
			AfxMessageBox("Can't Create Dump File");						
			return;
		}

		GetSystemInfo(&si);

		dwSize = TOTALVMRESERVE;
		memStep = VirtualAlloc(NULL, TOTALVMRESERVE, MEM_RESERVE, PAGE_NOACCESS);

		if(memStep == NULL)
			return;

		lpList = (LPVMOBJECT)memStep;
		lpUncommited = (LPVOID)memStep;

		lpMem =	0;
		dwIndex = 0;

		while(lpMem < si.lpMaximumApplicationAddress)
		{
			if(((int)lpList + 4096) >= ((int)memStep + TOTALVMRESERVE))
				return;

			if(lpList + sizeof(VMOBJECT) >= lpUncommited )
			{
				if( VirtualAlloc(lpUncommited,4096,MEM_COMMIT,PAGE_READWRITE) == NULL)
				{
					AfxMessageBox("A problem occurred during Memory Walking");						
					return;
				}

				lpUncommited = (LPVOID)((DWORD)lpList+ (DWORD)4096);
			}

			*lpList->szObjType = 0;
			*lpList->szModule = 0;
			*lpList->szSection = 0;
			lpList->bNew = 0;

			VirtualQueryEx(hProcess,lpMem,&(lpList->mbi),sizeof(MEMORY_BASIC_INFORMATION));

			lpMem = (LPVOID)((DWORD)lpList->mbi.BaseAddress +
				(DWORD)lpList->mbi.RegionSize);

			readBuff = VirtualAlloc(NULL,lpList->mbi.RegionSize,MEM_COMMIT,PAGE_READWRITE);

			ReadProcessMemory(hProcess,lpList->mbi.BaseAddress,readBuff,
				lpList->mbi.RegionSize,&dwBread);
			WriteFile(hFile,readBuff,dwBread,&dwBwrite,NULL);
			VirtualFree(readBuff,lpList->mbi.RegionSize, MEM_DECOMMIT);

			lpList++;
			++dwIndex;
		}

		CloseHandle(hProcess);
		CloseHandle(hFile);
		AfxMessageBox("Process Dumped Correctly!!!");
		//m_ListCtrl.DeleteAllItems();
		
		LoadProcesses();
	}
	
}


void CProcessListDlg::OnBnClickedButton2()
{
	HTREEITEM hItem  = pCtrl.GetSelectedItem();

	if (hItem == NULL)
	{
		AfxMessageBox("No Item Selected!");
		return;
	}


	CModuleDetails *pModuleInfo = reinterpret_cast<CModuleDetails *> (pCtrl.GetItemData(hItem ));
	if(pModuleInfo->IsProcessTrue())
	{
		GetDlgItem(IDC_BUTTON1)->EnableWindow(FALSE);
		pModuleInfo->TerminateProcess();
		m_ListCtrl.DeleteAllItems();
		AfxMessageBox("Process Terminated Reloading processes....");
		LoadProcesses();
	}
	else
	{
		AfxMessageBox("Can not Process Terminated....");		
	}

}

void CProcessListDlg::OnBnClickedButton3() // Produce Logs
{
	HANDLE hLog;
	DWORD dWritten;
	char Intestation1[] = "########################################\n";
	char Intestation2[] = ".::PMD Generated Log ::.\n";
	char Intestation3[] = "Process List:";
	char Intestation4[] = "Process Information:";  //Use only in IF
	char Intestation5[] = "Module List:";
	char Intestation6[] = "Module Information:";
	char Intestation7[] = "Module Exports:";
	TCHAR szDllBuffer[2048] = {0};
	
	
	//HTREEITEM hItem = pCtrl.GetSelectedItem();//Here you need to verify the empty selection
	//CModuleDetails *pModuleInfo = reinterpret_cast<CModuleDetails *> (pCtrl.GetItemData(hItem));
	
	if(transactionPID != NULL)
	{
		HTREEITEM hItem = pCtrl.GetSelectedItem();//Here you need to verify the empty selection
		CModuleDetails *pModuleInfo = reinterpret_cast<CModuleDetails *> (pCtrl.GetItemData(hItem));
		hLog = CreateFileA(pModuleInfo->GetModuleName() + ".log" ,
						GENERIC_WRITE,
						0,
						NULL,
						CREATE_ALWAYS,
						FILE_ATTRIBUTE_NORMAL,
						NULL);

		if(hLog == INVALID_HANDLE_VALUE)
			return;

		WriteFile(hLog,Intestation1,(DWORD)strlen(Intestation1),&dWritten,NULL);		
		WriteFile(hLog,Intestation2,(DWORD)strlen(Intestation2),&dWritten,NULL);		
		WriteFile(hLog,Intestation1,(DWORD)strlen(Intestation1),&dWritten,NULL);		
		WriteFile(hLog,Intestation3,(DWORD)strlen(Intestation3),&dWritten,NULL);
		
				
		CEnumProcessList * m_listp = new CEnumProcessList;
		CModuleDetails* pModuleData = new CModuleDetails;
		WriteFile(hLog,"\n",(DWORD)strlen("\n"),&dWritten,NULL);

		for(POSITION modulePos = m_listp->GetHeadPosition();modulePos!=NULL;) 
		{ 
			if ((pModuleData->GetFullFileName().GetLength()) != 0)
			{
				CString pID;
				CString modName = pModuleData->GetFullFileName() + "\n";
				pID.Format(_T("%04X"),pModuleData->pProcessID);
				modName = modName + " PID: " + pID + " ";
				WriteFile(hLog,modName,(DWORD)modName.GetLength(),&dWritten,NULL);
			}			
			
			pModuleData = m_listp->GetNext(modulePos);			
		}

		WriteFile(hLog,"\n\n",(DWORD)strlen("\n\n"),&dWritten,NULL);
		WriteFile(hLog,Intestation4,(DWORD)strlen(Intestation4),&dWritten,NULL);
		WriteFile(hLog,"\n\n",(DWORD)strlen("\n\n"),&dWritten,NULL);
		
		for (int i = 0; i < 20 ;i++)
		{
			CString nameItem ;
			CString valueItem;
			if((i == 19) || (i == 20))
			{
				nameItem = m_ListCtrl.GetItemText(i,0) + ":  ";
				WriteFile(hLog,nameItem,(DWORD)nameItem.GetLength(),&dWritten,NULL);
			}
			else
			{
				nameItem = m_ListCtrl.GetItemText(i,0) + ":  ";
				valueItem = m_ListCtrl.GetItemText(i,1) + " \n";
				WriteFile(hLog,nameItem,(DWORD)nameItem.GetLength(),&dWritten,NULL);
				WriteFile(hLog,valueItem,(DWORD)valueItem.GetLength(),&dWritten,NULL);
			}			
		}

		WriteFile(hLog,"\n\n",(DWORD)strlen("\n\n"),&dWritten,NULL);
		WriteFile(hLog,Intestation5,(DWORD)strlen(Intestation5),&dWritten,NULL);
		WriteFile(hLog,"\n\n",(DWORD)strlen("\n\n"),&dWritten,NULL);

		CEnumProcessList * m_listp1 =  new CEnumProcessList(transactionPID);		
		
		for(POSITION modulePos1 = m_listp1->GetHeadPosition();modulePos1!=NULL;)
		{
			CModuleDetails* pModuleData1 = new CModuleDetails;
			pModuleData = m_listp1->GetNext(modulePos1);
			CString nameModulus = pModuleData->GetFullFileName();			
			WriteFile(hLog,"\n",(DWORD)strlen("\n"),&dWritten,NULL);
			WriteFile(hLog,nameModulus,(DWORD)nameModulus.GetLength(),&dWritten,NULL);
		}

		m_ListCtrl2.GetItemText(itemSelection,0,szDllBuffer,sizeof(szDllBuffer));	
		
		if (strlen(szDllBuffer) != 0)
		{
			WriteFile(hLog,"\n\n",(DWORD)strlen("\n\n"),&dWritten,NULL);
			WriteFile(hLog,Intestation6,(DWORD)strlen(Intestation6),&dWritten,NULL);
			WriteFile(hLog,"\n\n",(DWORD)strlen("\n\n"),&dWritten,NULL);

			for (int i = 0; i < 12 ;i++)
			{
				CString nameItem ;
				CString valueItem;
				
				nameItem = m_List4.GetItemText(i,0) + ":  ";
				valueItem = m_List4.GetItemText(i,1) + " \n";
				WriteFile(hLog,nameItem,(DWORD)nameItem.GetLength(),&dWritten,NULL);
				WriteFile(hLog,valueItem,(DWORD)valueItem.GetLength(),&dWritten,NULL);				
			}

			WriteFile(hLog,"\n\n",(DWORD)strlen("\n\n"),&dWritten,NULL);
			WriteFile(hLog,Intestation7,(DWORD)strlen(Intestation7),&dWritten,NULL);
			WriteFile(hLog,"\n\n",(DWORD)strlen("\n\n"),&dWritten,NULL);

			for (int i = 0; i < m_List.GetItemCount() ;i++)
			{
				CString nameItem ;
				
				nameItem = m_List.GetItemText(i,0) + "\n";				
				WriteFile(hLog,nameItem,(DWORD)nameItem.GetLength(),&dWritten,NULL);				
			}



			itemSelection = NULL;
		}

		else
		{
			AfxMessageBox("Log Written!");
			CloseHandle(hLog);
			return;
		}

		AfxMessageBox("Log Written!");			
	}

	else
	{
		hLog = CreateFileA("BaseLog.log",
						GENERIC_WRITE,
						0,
						NULL,
						CREATE_ALWAYS,
						FILE_ATTRIBUTE_NORMAL,
						NULL);

		if(hLog == INVALID_HANDLE_VALUE)
			return;

		WriteFile(hLog,Intestation1,(DWORD)strlen(Intestation1),&dWritten,NULL);
		WriteFile(hLog,Intestation2,(DWORD)strlen(Intestation2),&dWritten,NULL);
		WriteFile(hLog,Intestation1,(DWORD)strlen(Intestation1),&dWritten,NULL);
		WriteFile(hLog,Intestation3,(DWORD)strlen(Intestation3),&dWritten,NULL);

		CEnumProcessList * m_listp = new CEnumProcessList;
		CModuleDetails* pModuleData = new CModuleDetails;
		
		WriteFile(hLog,"\n\n",(DWORD)strlen("\n\n"),&dWritten,NULL);

		for(POSITION modulePos = m_listp->GetHeadPosition();modulePos!=NULL;) 
		{ 
			if ((pModuleData->GetFullFileName().GetLength()) != 0)
			{
				CString pID;
				CString modName = pModuleData->GetFullFileName() + "\n";
				pID.Format(_T("%04X"),pModuleData->pProcessID);
				modName = modName + " PID: " + pID + " ";
				WriteFile(hLog,modName,(DWORD)modName.GetLength(),&dWritten,NULL);
			}			

			pModuleData = m_listp->GetNext(modulePos);			
		}

		AfxMessageBox("Log Written!");
		
	}

	CloseHandle(hLog);
	
}

DWORD CProcessListDlg::RvaToOffset(IMAGE_NT_HEADERS *NT, DWORD Rva)
{
	DWORD Offset = Rva, Limit;
	IMAGE_SECTION_HEADER *Img;
	WORD i;

	Img = IMAGE_FIRST_SECTION(NT);

	if (Rva < Img->PointerToRawData)
		return Rva;

	for (i = 0; i < NT->FileHeader.NumberOfSections; i++)
	{
		if (Img[i].SizeOfRawData)
			Limit = Img[i].SizeOfRawData;
		else
			Limit = Img[i].Misc.VirtualSize;

		if (Rva >= Img[i].VirtualAddress &&
			Rva < (Img[i].VirtualAddress + Limit))
		{
			if (Img[i].PointerToRawData != 0)
			{
				Offset -= Img[i].VirtualAddress;
				Offset += Img[i].PointerToRawData;
			}

			return Offset;
		}
	}

	return NULL;
}

void CProcessListDlg::OnLvnItemchangedList2(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
	TCHAR szDllBuffer[2048] = {0};
	HANDLE hFile;
	BYTE *BaseAddress;
	DWORD FileSize, BR, ET_Offset;	
	IMAGE_DOS_HEADER *ImageDosHeader;
	IMAGE_NT_HEADERS *ImageNtHeaders;
	IMAGE_EXPORT_DIRECTORY *ImageExportDir;
	DWORD *Functions, *Names;
	WORD *NameOrds, x, y;
	char *Name, *FName;

	int ItemSelected = pNMLV->iItem;
	itemSelection = pNMLV->iItem;
	m_ListCtrl2.GetItemText(ItemSelected,0,szDllBuffer,sizeof(szDllBuffer));	
	m_List4.DeleteAllItems();
	
	//Carve Export List
	
	hFile = CreateFileA(szDllBuffer,
					GENERIC_READ,
					FILE_SHARE_READ,
					0,
					OPEN_EXISTING,
					FILE_ATTRIBUTE_NORMAL,
					NULL);

	if(hFile == INVALID_HANDLE_VALUE)
	{
		AfxMessageBox("Unable to Open the Specified DLL!");
		return;
	}

	FileSize = GetFileSize(hFile, NULL);

	BaseAddress = (BYTE *) malloc(FileSize);	

	if (!ReadFile(hFile, BaseAddress, FileSize, &BR, NULL))
	{
		free(BaseAddress);
		CloseHandle(hFile);		
	}

	ImageDosHeader = (IMAGE_DOS_HEADER *) BaseAddress;
	
	ImageNtHeaders = (IMAGE_NT_HEADERS *)
		(ImageDosHeader->e_lfanew + (DWORD) ImageDosHeader);

	if (!ImageNtHeaders->OptionalHeader.DataDirectory
		[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress)
	{
		AfxMessageBox("This PE Doesn't contain an ET");
		free(BaseAddress);
		CloseHandle(hFile);
		return;
	}

	ET_Offset = RvaToOffset(ImageNtHeaders,
		ImageNtHeaders->OptionalHeader.DataDirectory
		[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress);

	if (ET_Offset == NULL)
	{
		AfxMessageBox("This PE Doesn't contain an ET");
		free(BaseAddress);
		CloseHandle(hFile);
		return;
	}

	ImageExportDir = (IMAGE_EXPORT_DIRECTORY *) (ET_Offset +
		(DWORD) BaseAddress);
	
	Name = (char *) (RvaToOffset(ImageNtHeaders,
		ImageExportDir->Name) + (DWORD) BaseAddress);

	Functions = (DWORD *) (RvaToOffset(ImageNtHeaders,
		ImageExportDir->AddressOfFunctions) + (DWORD) BaseAddress);

	Names = (DWORD *) (RvaToOffset(ImageNtHeaders,
		ImageExportDir->AddressOfNames) + (DWORD) BaseAddress);

	NameOrds = (WORD *) (RvaToOffset(ImageNtHeaders,
		ImageExportDir->AddressOfNameOrdinals) + (DWORD) BaseAddress);

	for (x = 0; x < ImageExportDir->NumberOfFunctions; x++)
	{		
		if (Functions[x] == 0)
			continue;
				
		for (y = 0; y < ImageExportDir->NumberOfNames; y++)
		{
			
			if (NameOrds[y] == x)
			{
				FName = (char *) (RvaToOffset(ImageNtHeaders,
					Names[y]) + (DWORD) BaseAddress);
			m_List.InsertItem(LVIF_STATE|LVIF_TEXT,y,FName,0,LVIS_SELECTED,0,0);			
			break;				
			}
		}
	}

	free(BaseAddress);
	CloseHandle(hFile);
	*pResult = 0;
	//////////////////////////////////////////////////////////////////////////
	///Details For 'Details Per Module'
	//////////////////////////////////////////////////////////////////////////
	
	CEnumProcessList * m_listp =  new CEnumProcessList(transactionPID);

	for(POSITION modulePos1 = m_listp->GetHeadPosition();modulePos1!=NULL;)
	{
		CModuleDetails* pModuleData = new CModuleDetails;
		pModuleData = m_listp->GetNext(modulePos1);
		CString nameModulus = pModuleData->GetFullFileName();
		if ((nameModulus.Compare(szDllBuffer) )== 0)
		{
			m_List4.InsertItem(LVIF_TEXT|LVIF_STATE, 0,"FullFileName",0, LVIS_SELECTED,0, 0);
			m_List4.SetItemText(0, 1, pModuleData->GetFullFileName());

			CString strFileSize;
			strFileSize.Format("%ld",pModuleData->GetFileSize());			
			m_List4.InsertItem(LVIF_TEXT|LVIF_STATE, 1,"FileSize",0, LVIS_SELECTED,0, 0);
			m_List4.SetItemText(1, 1, strFileSize);
			
			m_List4.InsertItem(LVIF_TEXT|LVIF_STATE, 2,"FileDescription",0, LVIS_SELECTED,0, 0);
			m_List4.SetItemText(2, 1, pModuleData->GetFileDescription());
			
			m_List4.InsertItem(LVIF_TEXT|LVIF_STATE, 3,"CompanyName",0, LVIS_SELECTED,0, 0);
			m_List4.SetItemText(3, 1, pModuleData->GetCompanyName());
			
			m_List4.InsertItem(LVIF_TEXT|LVIF_STATE, 4,"Comments",0, LVIS_SELECTED,0, 0);			
			m_List4.SetItemText(4, 1, pModuleData->GetComments());
			
			m_List4.InsertItem(LVIF_TEXT|LVIF_STATE, 5,"FileVersion",0, LVIS_SELECTED,0, 0);
			m_List4.SetItemText(5, 1, pModuleData->GetFileVersion());
			
			m_List4.InsertItem(LVIF_TEXT|LVIF_STATE, 4,"InternalName",0, LVIS_SELECTED,0, 0);
			m_List4.SetItemText(4, 1, pModuleData->GetInternalName());
			
			m_List4.InsertItem(LVIF_TEXT|LVIF_STATE, 5,"LegalCopyright	",0, LVIS_SELECTED,0, 0);
			m_List4.SetItemText(5, 1, pModuleData->GetLegalCopyright());
			
			m_List4.InsertItem(LVIF_TEXT|LVIF_STATE, 6,"LegalTrademarks",0, LVIS_SELECTED,0, 0);
			m_List4.SetItemText(6, 1, pModuleData->GetLegalTrademarks());
			
			m_List4.InsertItem(LVIF_TEXT|LVIF_STATE, 7,"OriginalFilename",0, LVIS_SELECTED,0, 0);
			m_List4.SetItemText(7, 1, pModuleData->GetOriginalFilename());
			
			m_List4.InsertItem(LVIF_TEXT|LVIF_STATE, 9,"PrivateBuild",0, LVIS_SELECTED,0, 0);
			m_List4.SetItemText(9, 1, pModuleData->GetPrivateBuild());
			
			m_List4.InsertItem(LVIF_TEXT|LVIF_STATE, 10,"ProductName",0, LVIS_SELECTED,0, 0);
			m_List4.SetItemText(10, 1, pModuleData->GetProductName());
			
			m_List4.InsertItem(LVIF_TEXT|LVIF_STATE, 11,"ProductVersion",0, LVIS_SELECTED,0, 0);
			m_List4.SetItemText(11, 1, pModuleData->GetProductVersion());
			
			m_List4.InsertItem(LVIF_TEXT|LVIF_STATE, 12,"SpecialBuild",0, LVIS_SELECTED,0, 0);
			m_List4.SetItemText(12	, 1, pModuleData->GetSpecialBuild());

			break;
		}
		
	}	
}

void CProcessListDlg::OnHdnItemclickList2(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMHEADER phdr = reinterpret_cast<LPNMHEADER>(pNMHDR);
	*pResult = 0;
}

void CProcessListDlg::OnBnClickedButton4() //Refresh Process List
{
	AfxMessageBox("Refreshing Process List..");
	if (LoadProcesses() == FALSE)
		AfxMessageBox("Unable To Refresh Process List");		
}
